package com.ys.util;

import com.alibaba.fastjson.JSONObject;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FileUtilYs {
	private static final Logger logger = LoggerFactory.getLogger(FileUtilYs.class);
	public static byte[] getBytesByFile(File file) throws IOException {
		FileInputStream fis = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
		try {
			fis = new FileInputStream(file);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			byte[] data = bos.toByteArray();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
			bos.close();
		}
		return null;
	}


	/**
	 * 上传网络文件到文件服务器
	 * @param url 网络文件网址
	 * @return
	 * @throws IOException
	 */
	public static R uploadFileByUrl(String url) throws IOException {

		//SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		//long moduleFile = idWorker.nextId();
		Map<String, String> sendParams = new HashMap<>();
		sendParams.put("urlOld",url);
		sendParams.put("moduleFile","tosProduct");
		logger.info("文件传输sendParams:\n"+sendParams);
		//String back = HttpUtilYs.sendHttpClientPost("https://file.mini-ease.com/api/outer/upload/uploadByUrl",  sendParams);
		String back = HttpUtilYs.sendHttpClientPost("http://52.83.116.16:8091/api/outer/upload/uploadByUrl",  sendParams);
		//JSONObject back = ApiHttpUtils.sendHttpClientPost("https://file.mini-ease.com/api/outer/upload/uploadByUrl",  sendParams);
		//{"msg":"操作成功","code":0,"data":{"url":"https://file.mini-ease.com/upload/1321067742207410176/2024/12/24/105135914.png"}}
		logger.info("文件传输back:\n"+back);
		if(back==null){
			throw new IOException("文件上传服务器失败");
		}
		JSONObject jsonObject = JSONObject.parseObject(back);
		JSONObject jsonObjectByData = JSONObject.parseObject(jsonObject.get("data").toString());
		return R.ok("成功",jsonObjectByData.get("url"));
		//return R.ok();
	}

}
